﻿// iMouseDown represents the current mouse button state: up or down
/*
lMouseState represents the previous mouse button state so that we can
check for button clicks and button releases:

if(iMouseDown && !lMouseState) // button just clicked!
if(!iMouseDown && lMouseState) // button just released!
*/
var mouseOffset = null;
var iMouseDown  = false;
var lMouseState = false;
var dragObject  = null;

// Demo 0 variables
var DragDrops   = [];
var curTarget   = null;
var lastTarget  = null;
var dragHelper  = null;
var tempDiv     = null;
var rootParent  = null;
var rootSibling = null;

Number.prototype.NaN0=function(){return isNaN(this)?0:this;}

function CreateDragContainer(){

	var cDrag        = DragDrops.length;
	DragDrops[cDrag] = [];

	for(var i=0; i<arguments.length; i++){
		var cObj = arguments[i];
		DragDrops[cDrag].push(cObj);
		cObj.setAttribute('DropObj', cDrag);

		for(var j=0; j<cObj.childNodes.length; j++){

			// Firefox puts in lots of #text nodes...skip these
			if(cObj.childNodes[j].nodeName=='#text') continue;

			cObj.childNodes[j].setAttribute('DragObj', cDrag);
		}
	}
}


function mouseCoords(ev){
	if(ev.pageX || ev.pageY){
		return {x:ev.pageX, y:ev.pageY};
	}
	return {
		x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
		y:ev.clientY + document.body.scrollTop  - document.body.clientTop
	};
}

function getMouseOffset(target, ev){
	ev = ev || window.event;

	var docPos    = getPosition(target);
	var mousePos  = mouseCoords(ev);
	return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}



function getPosition(e){
	var left = 0;
	var top  = 0;
	while (e.offsetParent){
		left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
		top  += e.offsetTop  + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);
		e     = e.offsetParent;
	}

	left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
	top  += e.offsetTop  + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);

	return {x:left, y:top};

}


function mouseMove(ev){
	ev         = ev || window.event;


	var target   = ev.target || ev.srcElement;
	var mousePos = mouseCoords(ev);

	if(lastTarget && (target!==lastTarget)){
		var origClass = lastTarget.getAttribute('origClass');
		if(origClass) lastTarget.className = origClass;
	}


	var dragObj = target.getAttribute('DragObj');


	if(dragObj!=null){
        target.style.cursor="move";

		if(target!=lastTarget){
			var oClass = target.getAttribute('overClass');
			if(oClass){
				target.setAttribute('origClass', target.className);
				target.className = oClass;
			}
		}


		if(iMouseDown && !lMouseState){
		
			curTarget     = target;

			rootParent    = curTarget.parentNode;
			rootSibling   = curTarget.nextSibling;

			mouseOffset   = getMouseOffset(target, ev);

			for(var i=0; i<dragHelper.childNodes.length; i++) dragHelper.removeChild(dragHelper.childNodes[i]);

			dragHelper.appendChild(curTarget.cloneNode(true));
			dragHelper.style.display = 'block';

			var dragClass = curTarget.getAttribute('dragClass');
			if(dragClass){
			
			    //
			    dragHelper.className="pagelist "+dragClass;
				
				//dragHelper.firstChild.className = dragClass;
			}

			dragHelper.firstChild.removeAttribute('DragObj');

			var dragConts = DragDrops[dragObj];

			curTarget.setAttribute('startWidth',  parseInt(curTarget.offsetWidth));
			curTarget.setAttribute('startHeight', parseInt(curTarget.offsetHeight));
			curTarget.style.display  = 'none';

			for(var i=0; i<dragConts.length; i++){
				with(dragConts[i]){
					var pos = getPosition(dragConts[i]);

					setAttribute('startWidth',  parseInt(offsetWidth));
					setAttribute('startHeight', parseInt(offsetHeight));
					setAttribute('startLeft',   pos.x);
					setAttribute('startTop',    pos.y);
				}

				for(var j=0; j<dragConts[i].childNodes.length; j++){
					with(dragConts[i].childNodes[j]){
						if((nodeName=='#text') || (dragConts[i].childNodes[j]==curTarget)) continue;

						var pos = getPosition(dragConts[i].childNodes[j]);

						// save the width, height and position of each element
						setAttribute('startWidth',  parseInt(offsetWidth));
						setAttribute('startHeight', parseInt(offsetHeight));
						setAttribute('startLeft',   pos.x);
						setAttribute('startTop',    pos.y);
					}
				}
			}
		}
	}

	if(curTarget){
		dragHelper.style.top  = mousePos.y - mouseOffset.y;
		dragHelper.style.left = mousePos.x - mouseOffset.x;

		var dragConts  = DragDrops[curTarget.getAttribute('DragObj')];
		var activeCont = null;

		var xPos = mousePos.x - mouseOffset.x + (parseInt(curTarget.getAttribute('startWidth')) /2);
		var yPos = mousePos.y - mouseOffset.y + (parseInt(curTarget.getAttribute('startHeight'))/2);

		for(var i=0; i<dragConts.length; i++){
			with(dragConts[i]){
				if(((getAttribute('startLeft'))                               < xPos) &&
					((getAttribute('startTop'))                                < yPos) &&
					((getAttribute('startLeft') + getAttribute('startWidth'))  > xPos) &&
					((getAttribute('startTop')  + getAttribute('startHeight')) > yPos)){

						activeCont = dragConts[i];
						break;
				}
			}
		}

		if(activeCont){
			var beforeNode = null;

			for(var i=activeCont.childNodes.length-1; i>=0; i--){
				with(activeCont.childNodes[i]){
					if(nodeName=='#text') continue;

					if(
						curTarget != activeCont.childNodes[i]                              &&
						((getAttribute('startLeft') + getAttribute('startWidth'))  > xPos) &&
						((getAttribute('startTop')  + getAttribute('startHeight')) > yPos)){
							beforeNode = activeCont.childNodes[i];
					}
				}
			}

			if(beforeNode){
				if(beforeNode!=curTarget.nextSibling){
					activeCont.insertBefore(curTarget, beforeNode);
				}

			} else {
				if((curTarget.nextSibling) || (curTarget.parentNode!=activeCont)){
					activeCont.appendChild(curTarget);
				}
			}

			if(curTarget.style.display!=''){
				curTarget.style.display  = '';
				//alert(parseInt(curTarget.offsetHeight)-20);
				curTarget.style.border="dashed 1px #ff99cc";
			}
		} else {
			if(curTarget.style.display!='none'){
				curTarget.style.display  = 'none';
			}
		}
	}
	lMouseState = iMouseDown;
	lastTarget  = target;
	lMouseState = iMouseDown;
	return false;
}

function mouseUp(ev){
	if(curTarget){
		dragHelper.style.display = 'none';
		if(curTarget.style.display == 'none'){
			if(rootSibling){
				rootParent.insertBefore(curTarget, rootSibling);
			} else {
				rootParent.appendChild(curTarget);
			}
		}

		// make sure the drag item is visible
		curTarget.style.display = '';
		//crl add;
		curTarget.style.border="dashed 1px #fff";
		
		sortItem(curTarget.parentNode);
	}
	curTarget  = null;
	iMouseDown = false;
}

//重新排序列表;不过并未保存;
function sortItem(listParent){
    var list=listParent.childNodes;
    for(var i=0;i<list.length;i++){
        var textareaList= $as.call(list[i],"textarea")
        for(var j in textareaList){
        
            if(j=="index"){
                textareaList[j].value=i+1;
            }
            
        }//j for end;
        
    }//i for end;
    
    
    //是否存在的保存按钮,也用于退出时的提示;
    if($("saveAllPane")==null){
        var savePane=document.createElement("div");
        savePane.setAttribute("id","saveAllPane");
        var saveBtn=document.createElement("button");
        var cancelBtn=document.createElement("button");
        saveBtn.onclick=function(){
            $("wrapper").removeChild(savePane);
            for(var i=0;i<list.length;i++){
                var alist=$as.call(list[i],"a");
                for(var j=0;j<alist.length;j++){
                    var abj=alist[j];
                    var href=abj.getAttribute("href");
                    if(href.indexOf("updatePage.xhtml?Pid")>-1){
                         abj.onclick();
                    }
                }
            }
        }
        cancelBtn.onclick=function(){
            $("wrapper").removeChild(savePane);
        }
        
        var saveText=document.createTextNode("全部保存");
        var cancelText=document.createTextNode("不保存");
        
        cancelBtn.setAttribute("type","button");
        saveBtn.setAttribute("type","button");
        
        saveBtn.appendChild(saveText);
        cancelBtn.appendChild(cancelText);
        
        savePane.appendChild(saveBtn);
        savePane.appendChild(cancelBtn);
        $("wrapper").insertBefore(savePane,$("sitebody"));
    }
}

function mouseDown(){
	iMouseDown = true;
	if(lastTarget){
		return false;
	}
}



function initDarg(){
    document.onmousemove = mouseMove;
    document.onmousedown = mouseDown;
    document.onmouseup   = mouseUp;

	dragHelper = document.createElement('DIV');
	dragHelper.style.cssText = 'position:absolute;display:none;';
	
	CreateDragContainer($('pagelist'));

	document.body.appendChild(dragHelper);
}
function clearAndSave(){
    if($("saveAllPane")!=null){
        alert("你还未保存");
        return false;
    }
    return true;
}

addLoadEvent(initDarg);
addUnLoadEvent(clearAndSave);